library(tidyverse) # for data cleaning and plotting
library(gardenR) # for Lisa's garden data
library(lubridate) # for date manipulation
library(openintro) # for the abbr2state() function
library(palmerpenguins)# for Palmer penguin data
library(maps) # for map data
library(ggmap) # for mapping points on maps
library(gplots) # for col2hex() function
library(RColorBrewer) # for color palettes
library(sf) # for working with spatial data
library(leaflet) # for highly customizable mapping
library(ggthemes) # for more themes (including theme_map())
library(plotly) # for the ggplotly() - basic interactivity
library(gganimate) # for adding animation layers to ggplots
library(transformr) # for "tweening" (gganimate)
library(gifski) # need the library for creating gifs but don't need to load each time
library(shiny) # for creating interactive apps
library(directlabels) # for geom_dl
theme_set(theme_minimal())
# SNCF Train data
small_trains <- read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2019/2019-02-26/small_trains.csv")
# Lisa's garden data
data("garden_harvest")
# Lisa's Mallorca cycling data
mallorca_bike_day7 <- read_csv("https://www.dropbox.com/s/zc6jan4ltmjtvy0/mallorca_bike_day7.csv?dl=1") %>%
select(1:4, speed)
# Heather Lendway's Ironman 70.3 Pan Am championships Panama data
panama_swim <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_swim_20160131.csv")
panama_bike <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_bike_20160131.csv")
panama_run <- read_csv("https://raw.githubusercontent.com/llendway/gps-data/master/data/panama_run_20160131.csv")
#COVID-19 data from the New York Times
covid19 <- read_csv("https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv")
Go here or to previous homework to remind yourself how to get set up.
Once your repository is created, you should always open your project rather than just opening an .Rmd file. You can do that by either clicking on the .Rproj file in your repository folder on your computer. Or, by going to the upper right hand corner in R Studio and clicking the arrow next to where it says Project: (None). You should see your project come up in that list if you’ve used it recently. You could also go to File –> Open Project and navigate to your .Rproj file.
Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
NEW!! With animated graphs, add eval=FALSE to the code chunk that creates the animation and saves it using anim_save(). Add another code chunk to reread the gif back into the file. See the tutorial for help.
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
ggplotly() function.home_owner <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-02-09/home_owner.csv')
home_ownership_race <- home_owner %>%
mutate(home_owner = home_owner_pct * 100) %>%
ggplot(aes(x = year, y = home_owner, color = race)) +
geom_line(aes(linetype = race, size = race)) +
scale_linetype_manual(values = c("solid", "solid", "solid")) +
scale_color_manual(values = c("peru", "steelblue4", "coral4")) +
scale_size_manual(values = c(1.25, 1.25, 1.25)) +
geom_dl(aes(label = race), method = list(dl.trans(x = x + 0.2), "last.points", cex = 1.25)) +
theme(plot.background = element_rect("snow2"),
panel.background = element_rect("snow2"),
panel.border = element_rect(fill = NA, color = "gray80"),
panel.grid.major = element_line("gray80"),
panel.grid.minor = element_blank(),
axis.line = element_line(size = 0.5,
linetype = "solid",
colour = "gray80"),
legend.position = "none") +
xlim(1976, 2021)+
labs(title = "US Homeownership by Race/Ethnicity",
subtitle = "Percentages from 1976 - 2016",
caption = "Josh Fortin | Data: US Census, Urban Institute",
color = "",
x = "",
y = "")
ggplotly(home_ownership_race)
lettuce <- garden_harvest %>%
filter(vegetable == "lettuce") %>%
count(variety, name = "var_count") %>%
arrange(desc(var_count)) %>%
ggplot(aes(x = var_count, y = variety)) +
geom_col() +
labs(title = "Lettuce Harvests by Species",
x = "Number of Times Each Species was Harvested",
y = "Lettuce Species")
ggplotly(lettuce)
small_trains dataset that contains data from the SNCF (National Society of French Railways). These are Tidy Tuesday data! Read more about it here.small_trains %>%
filter(departure_station == "PARIS EST") %>%
group_by(year, arrival_station) %>%
summarize(avg_delay = mean(avg_delay_all_departing)) %>%
ggplot(aes(x = year, y = avg_delay, color = arrival_station)) +
geom_line(size = 1.3) +
labs(title = "Average Delay (Min) of All Departing Trains from PARIS EST Station",
subtitle = "Year: {frame_along}",
x = "",
y = "",
color = "Arrival Station") +
transition_reveal(year)
anim_save("train_animation.gif")
knitr::include_graphics("train_animation.gif")
geom_area() examples here). You will look at cumulative harvest of tomato varieties over time. You should do the following:garden_harvest data, filter the data to the tomatoes and find the daily harvest in pounds for each variety.fct_reorder()) from most to least harvested (most on the bottom).I have started the code for you below. The complete() function creates a row for all unique date/variety combinations. If a variety is not harvested on one of the harvest dates in the dataset, it is filled with a value of 0.
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
group_by(date, variety) %>%
summarize(daily_harvest_lb = sum(weight)*0.00220462) %>%
ungroup() %>%
complete(variety, date, fill = list(daily_harvest_lb = 0)) %>%
group_by(variety) %>%
mutate(cum_harvest_lbs = cumsum(daily_harvest_lb)) %>%
ungroup() %>%
mutate(variety_reorder = fct_reorder(variety, daily_harvest_lb, sum, .desc = FALSE)) %>%
ggplot(aes(x = date, y = cum_harvest_lbs, fill = variety_reorder)) +
scale_fill_brewer(palette = "Paired") +
geom_area() +
labs(title = "Cumulative Harvest (lbs) of Tomato Varieties Over Time",
subtitle = "Date: {frame_along}",
x = "",
y = "") +
transition_reveal(date)
anim_save("tomato_cumsum.gif")
knitr::include_graphics("tomato_cumsum.gif")
mallorca_bike_day7 bike ride using animation! Requirements:ggmap.ggimage package and geom_image to add a bike image instead of a red point. You can use this image. See here for an example.mallorca_map <- get_stamenmap(
bbox = c(left = 2.28, bottom = 39.41, right = 3.03, top = 39.8),
maptype = "terrain",
zoom = 11
)
ggmap(mallorca_map) +
geom_path(data = mallorca_bike_day7,
aes(x = lon, y = lat, color = ele),
size = .3) +
geom_point(data = mallorca_bike_day7,
aes(x = lon, y = lat),
color = "red") +
scale_color_viridis_c(option = "plasma") +
transition_reveal(along = time) +
labs(title = "Mallorca Bike Ride",
subtitle = "Time: {frame_along}",
color = "Elevation") +
theme_map() +
theme(legend.background = element_blank(),
plot.background = element_rect(color = "lightgrey"))
anim_save("mallorca_map.gif")
knitr::include_graphics("mallorca_map.gif")
I prefer a static map because it is easier for the audience to interpret since there are less things happening on the screen. While this makes for a great visualization, the moving nature of the visual makes it hard to interpret the bike data, in this case while looking at elevation.
panama_swim, panama_bike, and panama_run. Create a similar map to the one you created with my cycling data. You will need to make some small changes: 1. combine the files (HINT: bind_rows(), 2. make the leading dot a different color depending on the event (for an extra challenge, make it a different image using `geom_image()!), 3. CHALLENGE (optional): color by speed, which you will need to compute on your own from the data. You can read Heather’s race report here. She is also in the Macalester Athletics Hall of Fame and still has records at the pool.panama_map <- get_stamenmap(
bbox = c(left = -79.6651, bottom = 8.8411, right = -79.4508, top = 9.0246),
maptype = "terrain",
zoom = 12
)
panama_bind <- bind_rows(list(panama_bike, panama_run, panama_swim), .id = NULL)
ggmap(panama_map) +
geom_path(data = panama_bind,
aes(x = lon, y = lat)) +
geom_point(data = panama_bind,
aes(x = lon, y = lat, color = event)) +
theme_map() +
transition_reveal(along = time) +
labs(title = "Heather Lendway's Ironman 70.3 Pan Am Championship",
subtitle = "Time: {frame_along}",
color = "Event")
anim_save("ironman.gif")
knitr::include_graphics("ironman.gif")
lag() function you’ve used in a previous set of exercises). Replace missing values with 0’s using replace_na().geom_path() and add a group aesthetic. Put the x and y axis on the log scale and make the tick labels look nice - scales::comma is one option. This plot will look pretty ugly as is.geom_point()) and add the state name as a label (geom_text() - you should look at the check_overlap argument).animate() function to have 200 frames in your animation and make it 30 seconds long.covid_plot1 <- covid19 %>%
filter(cases > 20) %>%
group_by(state) %>%
mutate(cases_lag_7day = lag(cases, 7, order_by = date)) %>%
replace_na(list(cases_lag_7day = 0)) %>%
mutate(new_7day = (cases - cases_lag_7day)) %>%
ggplot(aes(x = cases, y = new_7day, group = state, color = state)) +
geom_path() +
geom_point() +
geom_text(aes(label = state)) +
scale_y_log10(labels = scales::comma) +
scale_x_log10(labels = scales::comma) +
transition_reveal(along = date) +
theme(legend.position = "none") +
labs(title = "COVID19 Trajectory: Confirmed Cases",
subtitle = "Date: {frame_along}",
x = "Cumulative Cases",
y = "New Cases in Past Week")
animate(plot = covid_plot1, nframes = 200, duration = 30)
anim_save("covid_plo1.gif")
knitr::include_graphics("covid_plo1.gif")
From this visualization, I observe that in general, there is an increasing trend in new cases per week as cumulative cases increase across all states. However, there is obviously variablity within the dataset, most notable in the US territories such as Guam, the Virgin Islands, and the Northern Mariana islands especially. These territories don’t have as high of new cases each week as the states do, likely because of their isolated geography and relatively small populations.
states_map data. Here is a list of details you should include in the plot:wday() to create a day of week variable and filter to all the Fridays.animate() function to make the animation 200 frames instead of the default 100 and to pause for 10 frames on the end frame.group = date in aes().census_pop_est_2018 <- read_csv("https://www.dropbox.com/s/6txwv3b4ng7pepe/us_census_2018_state_pop_est.csv?dl=1") %>%
separate(state, into = c("dot","state"), extra = "merge") %>%
select(-dot) %>%
mutate(state = str_to_lower(state))
states_map <- map_data("state")
covidplot2 <- covid19 %>%
mutate(day_week = wday(date, label = TRUE)) %>%
filter(day_week == "Fri") %>%
mutate(state_lower = str_to_lower(state)) %>%
select(-state) %>%
group_by(state_lower) %>%
left_join(census_pop_est_2018,
by = c("state_lower" = "state")) %>%
mutate(covid_per_10000 = (cases/est_pop_2018)*10000) %>%
ggplot() +
geom_map(map = states_map,
aes(map_id = state_lower,
fill = covid_per_10000,
group = date)) +
expand_limits(x = states_map$long, y = states_map$lat) +
theme_map() +
theme(legend.position = "top") +
scale_fill_continuous(type = "viridis") +
labs(title = "Cumulative COVID19 Cases per 10,000 People",
subtitle = "Date: {frame_time}",
fill = "") +
transition_time(date)
animate(plot = covidplot2, nframes = 200, end_pause = 10)
anim_save("covid_plo2.gif")
knitr::include_graphics("covid_plo2.gif")
In this plot, we can see that certain states, such as North and South Dakota, quickly become some are the states with the largest covid cases per 10,000 residents, likely due to some of the government policies put in place by state governers. Additionally, we can see some regional patterns in the data, such as the Pacific Northwest and Northeast having relatively lower covid cases per 10,000 people compared to areas such as the South and Midwest.
shiny app (for next week!)NOT DUE THIS WEEK! If any of you want to work ahead, this will be on next week’s exercises.
app.R file you create. Below, you will post a link to the app that you publish on shinyapps.io. You will create an app to compare states’ cumulative number of COVID cases over time. The x-axis will be number of days since 20+ cases and the y-axis will be cumulative cases on the log scale (scale_y_log10()). We use number of days since 20+ cases on the x-axis so we can make better comparisons of the curve trajectories. You will have an input box where the user can choose which states to compare (selectInput()) and have a submit button to click once the user has chosen all states they’re interested in comparing. The graph should display a different line for each state, with labels either on the graph or in a legend. Color can be used if needed.DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?